package controllers

import (
	"github.com/goravel/framework/contracts/http"
	"github.com/goravel/framework/facades"
	httpfacade "github.com/hulutech-web/http_result"
	"github.com/spf13/cast"
	"goravel/app/http/requests"
	"goravel/app/models"
)

type DeviceController struct {
	//Dependent services
	SearchByParamsService
}

func NewDeviceController() *DeviceController {
	return &DeviceController{
		//Inject services
	}
}

// Index 设备分页查询，支持搜索，路由参数?name=xxx&pageSize=1&currentPage=1&sort=xxx&order=xxx,等其他任意的查询参数
// @Summary      设备分页查询
// @Description  设备分页查询
// @Tags         设备分页查询
// @Accept       json
// @Produce      json
// @Security ApiKeyAuth
// @Param Authorization header string false "Bearer 用户令牌"
// @Param  name  query  string  false  "name"
// @Param  pageSize  query  string  false  "pageSize"
// @Param  currentPage  query  string  false  "currentPage"
// @Param  sort  query  string  false  "sort"
// @Param  order  query  string  false  "order"
// @Success 200 {string} json "{"code":"200", "data":"response data"}"
// @Router       /api/device [get]
func (r *DeviceController) Index(ctx http.Context) http.Response {

	devices := []models.Device{}
	queries := ctx.Request().Queries()
	result, _ := httpfacade.NewResult(ctx).SearchByParams(queries, map[string]interface{}{}).ResultPagination(&devices)
	return result
}

func (r *DeviceController) Store(ctx http.Context) http.Response {
	var deviceRequest requests.DeviceRequest
	errors, err := ctx.Request().ValidateRequest(&deviceRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	facades.Orm().Query().Model(&models.Device{}).Create(&models.Device{
		Code:          deviceRequest.Code,
		Name:          deviceRequest.Name,
		BoardModel:    deviceRequest.BoardModel,
		Address:       deviceRequest.Address,
		BatteryStatus: deviceRequest.BatteryStatus,
		Spec:          deviceRequest.Spec,
		TowerCode:     deviceRequest.TowerCode,
		SerialNumber:  deviceRequest.SerialNumber,
	})
	return httpfacade.NewResult(ctx).Success("添加成功", nil)
}

func (r *DeviceController) Update(ctx http.Context) http.Response {
	id := ctx.Request().Route("id")
	var deviceRequest requests.DeviceRequest
	errors, err := ctx.Request().ValidateRequest(&deviceRequest)
	if err != nil {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据错误", err.Error())
	}
	if errors != nil {
		return httpfacade.NewResult(ctx).ValidError("", errors.All())
	}
	var device models.Device
	facades.Orm().Query().Model(&models.Device{}).Where("id=?", id).First(&device)
	if device.ID == 0 {
		return httpfacade.NewResult(ctx).Error(http.StatusInternalServerError, "数据不存在", err.Error())
	}
	device.Code = deviceRequest.Code
	device.Name = deviceRequest.Name
	device.BoardModel = deviceRequest.BoardModel
	device.Address = deviceRequest.Address
	device.BatteryStatus = deviceRequest.BatteryStatus
	device.Spec = deviceRequest.Spec
	device.TowerCode = deviceRequest.TowerCode
	device.SerialNumber = deviceRequest.SerialNumber
	facades.Orm().Query().Model(&models.Device{}).Where("id=?", id).Save(&device)
	return httpfacade.NewResult(ctx).Success("修改成功", nil)
}

func (r *DeviceController) Destroy(ctx http.Context) http.Response {
	id := ctx.Request().Route("id")
	facades.Orm().Query().Delete(&models.Device{}, id)
	return httpfacade.NewResult(ctx).Success("删除成功", nil)
}

func (r *DeviceController) List(ctx http.Context) http.Response {
	start_at := ctx.Request().Query("start_at", "")
	end_at := ctx.Request().Query("end_at", "")
	devices := []models.Device{}
	if start_at != "" && end_at != "" {
		facades.Orm().Query().Where("online_at >=?", start_at).Where("online_at<=?", end_at).Find(&devices)
	} else {
		facades.Orm().Query().Find(&devices)
	}
	return ctx.Response().Success().Json(devices)
}

func (r *DeviceController) BindUser(ctx http.Context) http.Response {
	id := ctx.Request().Input("id")
	user_id := ctx.Request().Input("user_id")
	if id == "" || user_id == "" {
		return httpfacade.NewResult(ctx).Error(500, "参数错误", nil)
	}
	device := models.Device{}
	facades.Orm().Query().Model(&models.Device{}).Where("id=?", id).First(&device)
	if device.ID == 0 {
		return httpfacade.NewResult(ctx).Error(500, "设备不存在", nil)
	}
	userid := cast.ToUint(user_id)
	device.UserID = userid
	//更新
	facades.Orm().Query().Model(&device).Update("user_id", userid)

	return httpfacade.NewResult(ctx).Success("设备绑定成功", nil)
}
